package studentManager2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

public class DBUtil {
	static {// 静态块
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		} catch (ClassNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();

		}
	}

	private DBUtil() {
	}

	final static String url = "jdbc:sqlserver://localhost:1433;DatabaseName=test";

	public static Connection getConnection() {
		try {
			return DriverManager.getConnection(url, "java46", "java46");
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return null;
	}

	public static void closeAll(ResultSet r, Statement s, Connection c) {
		close(r);
		close(s);
		close(c);
	}

	public static void close(ResultSet r) {
		if (r != null)
			try {
				r.close();
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
	}

	public static void close(Statement r) {
		if (r != null)
			try {
				r.close();
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
	}

	public static void close(Connection r) {
		if (r != null)
			try {
				r.close();
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
	}

	public static int executeUpdate(String sql, Object... args) {
		Connection con = getConnection();
		PreparedStatement ps = null;
		try {
			ps = con.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				// 有一些属性需要单独处理
				// if (args[i] instanceof java.util.Date) {
				// java.util.Date d = (Date) args[i];
				// ps.setDate(i + 1,
				// d == null ? null : new java.sql.Date(d.getTime()));
				// continue;
				// }
				ps.setObject(i + 1, args[i]);
			}
			return ps.executeUpdate();
		} catch (SQLException e) {
			// 忽略异常
			e.printStackTrace();
		} finally {
			close(ps);
			close(con);
		}
		return 0;
	}

	public static Vector select(String sql, Object... args) {
		Connection con = getConnection();
		PreparedStatement ps = null;
		ResultSet r = null;
		Vector vs = null;
		try {
			ps = con.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			r = ps.executeQuery();
			vs = new Vector();
			while (r.next()) {
				Vector v = new Vector();
				v.add(r.getString("id"));
				v.add(r.getString("name"));
				v.add(r.getString("sex"));
				v.add(r.getInt("age"));
				v.add(r.getString("jiGuan"));
				v.add(r.getString("dept"));
				vs.add(v);
				System.out.println(v.toString());
			}
		} catch (SQLException e) {
			// 忽略异常
			e.printStackTrace();
		} finally {
			close(r);
			close(ps);
			close(con);
		}
		return vs;
	}
}
